package com.doitedu.mr.day07.join;

import com.doitedu.mr.day06.yarn.WordCountMapper;
import com.doitedu.mr.day06.yarn.WordCountReducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2021/12/9
 * @Created by HANGGE
 * @Description TODO
 * map端join
 */
public class Join {
    static  class JoinMapper extends Mapper<LongWritable ,Text , Text, NullWritable> {
        Map<String, String> mp =  new HashMap<>();
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            // 使用本地流读取用户数据  将用户存储在Map集合中
            BufferedReader br = new BufferedReader(new FileReader("user.txt"));
            String line = null;
            while((line = br.readLine())!=null){
                String uid = line.split(",")[0];
                mp.put(uid,line) ;
            }
        }

        // 只加载订单数据
        Text k = new Text() ;
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //order012 u001
            String line = value.toString();
            String uid = line.split("\\s+")[1];
            // 根据uid获取用户信息
            String user = mp.get(uid);
            String res = user+","+line ;
            k.set(res);
            // 输出数据
            context.write(k, NullWritable.get());
        }
    }

    public static void main(String[] args) throws Exception{
        Configuration conf = new Configuration();
        // 一 设置提交的运行模式    默认是本地
        conf.set("mapreduce.framework.name","yarn");

        // 1  创建 JOB
        Job job = Job.getInstance(conf, "mapside_join");
        // 分布式缓存   设置user数据为分布式缓存数据 , 数据就会缓存在所有的运行MT的机器的类路径下
        job.addCacheFile(new URI("hdfs://linux01:8020/data/user.txt"));
        job.setJarByClass(Join.class);
        // 1) Mapper 类
        job.setMapperClass(JoinMapper.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
      // 只有订单
        FileInputFormat.setInputPaths(job , new Path("/data/join/"));
        // 6) 设置输出的结果保存路径
        FileOutputFormat.setOutputPath(job, new Path("/data/join_res/"));
        job.waitForCompletion(true) ;
    }

}
